from rlcore import *
from rlinterface import *

from rlsdl import SdlInterface
from rlfov import Fov

from rlfov import Wheel, WheelIndex

from rltext import TextFormatting

from erlitem import *
from erlmenu import *

from erlrays import *

import random
from math import pi

from erldevice import *
from erlcomponents import *

from erlglobals import *

from erlserial import *

import sys



def layoutInterface( interface ):
	pass

#for i in range(10):
#	x, y = hollowLevel.getRandomTileOfType( GTT.floor )
#	tile = hollowLevel.tiles[x][y]
#	itemType = random.choice( [ ItemTable.Coal, ItemTable.Iron, ItemTable.Brass ] )
#	item = ItemStack( itemType, random.randint(10,200) )
#	hollowLevel.putItem( item, x, y )
#rgProjector = cFreeEnergyLineProjector()
#rgTrigger = cTrigger()
#rgTrigger = cSignalGenerator()
#rgTrigger["destination"] = HardcodedValue( rgProjector )
#raygunParts = [ rgTrigger, rgProjector ]
#x, y = hollowLevel.getRandomTileOfType( GTT.floor )

from erlmenu import WrapForDialog

class InfoElement (InterfaceElement):
	def __init__(self, interface, name, player = None):
		InterfaceElement.__init__(self, interface, name)
		self.colour = 0x69, 0x36, 0x03
		self.player = player
	def draw(self):
		for y in range(self.yLayout, self.yLayout + self.height):
			self.interface.move( self.xLayout, y )
			self.interface.putString( " " * self.width, Glyph(' ', self.colour, self.colour ) )
		if self.player:
			text = "%s<N>HP: %d/%d<N>Depth: %d" % (self.player.name, self.player.hp, self.player.maxHp, self.player.game.getLevelIndex( self.player.level ) + 1 )
			contentLength = self.width - 2 
			y = self.yLayout 
			for length, line in WrapForDialog( text, contentLength ):
				offset = (contentLength-length)/2
				self.interface.move( self.xLayout + 1 + offset, y )
				self.interface.putFormattedText( line, defaultForeground=(255,255,255), defaultBackground=self.colour )
				y += 1
			

screen = SdlInterface( "EngineRL", screenSize, ("data/VeraMono.ttf",18), layoutInterface, keyboardRepeatDelay = 0.40 )
#screen = SdlInterface( "EngineRL", screenSize, ("data/AurulentSansMono-Regular.otf",18), layoutInterface )
#screen = SdlInterface( "EngineRL", screenSize, ("data/txtt.pfb",18), layoutInterface )
#screen = SdlInterface( "EngineRL", screenSize, ("data/VeraMoBd.ttf",16), layoutInterface )

def createChickenAt( x, y ):
	NonPC( position=(x,y), ai = aiRandomWalk, level=hollowLevel, timekeeper=timekeeper, name="chicken", glyph=Glyph( 'c', (255,255,0) ), mobility = standardTraversibility )


class Messages:
	def __init__(self):
		self.messages = []
	def add(self, message):
		self.messages.append( message )
	def show(self):
		displayText = " ".join( self.messages )
		self.messages = []
		if displayText:
			DisplayTextInputHandler( screen, screen.elements["text"], displayText )

screen.messages = Messages()

		
#class Pushable ( NonPC ):
#	def __init__(self, *args, **kwargs):
#		NonPC.__init__( self, *args, **kwargs )
#		self.mayDisplace = True
#		self.paintHighlights = True
#	def tryPush(self, direction):
#		target = self.getTileRelative( direction )
#		if self.mayMove( target ):
#			self.moveRelative( direction )
#			return True
#		return False
#	def die(self):
#		pass


## at = PlayerCharacter( "at", hollowLevel, viewport = screen.elements["map"] )
#raygun = Device( screen,
#		name = Noun( short=("a","raygun","rayguns") ),
#		glyph = Glyph( '/', (255,255,0) ),
#		components = raygunParts )
#firstRaygun = HandheldDevice( chassisHandheld, raygun )
#secondRaygun = HandheldDevice( chassisHandheld, raygun )
#hollowLevel.putItem( firstRaygun, at.x, at.y )
#hollowLevel.putItem( secondRaygun, at.x, at.y )

### :( # cart = Pushable( position=None, ai = aiPassive, level=hollowLevel, timekeeper=timekeeper, name="cart", glyph=Glyph( '~', stdDeviceColour, stdCartBackground ), mobility = standardTraversibility )

screen.start()


#mainInput = MainInputHandler( screen, at, timekeeper )

import erlgame

globalGame = None
savegameName = None

class EndGameReally: pass

def startGame():
	def endGame():
		raise EndGameReally()
	try:
		globalGame.gameloop()
	except PlayerDead:
		text = []
		text.append( "<DARKBRASS>Game over</DARKBRASS>" )
		TextDisplay( interface=screen, text="<N>".join(text), width=60, name="dead-title-screen", onDismiss=endGame)
	except PlayerQuit:
		globalGame.save( savegameName )
	except PlayerWon:
		text = []
		text.append( "<DARKBRASS>Congratulations!</DARKBRASS>" )
		text.append( "You've won the game! The <DARKBRASS>Emperor Engine</DARKBRASS> is destroyed, and the continent is safe once more." )
		TextDisplay( interface=screen, text="<N>".join(text), width=60, name="won-title-screen", onDismiss=endGame)

def gotName( name ):
	import os
	import os.path

	global globalGame, savegameName


	ViewportElement( screen, "map", (0,0)
		).move( 0, 0 ).resize( levelWidth, levelHeight )
	WrappedTextElement( screen, "text", [ TextFormatting("BLACK"), " ", TextFormatting("BGBLUE"), "[MORE]",  TextFormatting("/BGBLUE"), TextFormatting("/BLACK") ], fgColour = (200,200,200), bgColour=(0x79,0x46,0x13)
		).move( levelWidth + 1, 4 ).resize( screenWidth - levelWidth - 1, screenHeight - 4 )
	InfoElement( screen, "info" ).move( levelWidth + 1, 0 ).resize( screenWidth - levelWidth - 1, 4 )
	ColourElement( screen, "splitter", (0x69,0x36,0x03) ).move( levelWidth, 0 ).resize( 1, screenHeight )
	
	savegameName = "./savegame/erl-%s.savegame" % name
	print "Trying to load \"%s\"..." % savegameName,
	sys.stdout.flush()
	if os.path.exists (savegameName ):
		print "which exists...",
		sys.stdout.flush()
		try:
			globalGame = erlgame.loadGame( gameVersion, savegameName, screen )
			print "and is valid."
			sys.stdout.flush()
			os.unlink( savegameName )
			print "Game loaded. Old savegame removed."
			sys.stdout.flush()
			text = []
			text.append( "<DARKBRASS>Game loaded</DARKBRASS>" )
			text.append( "Welcome back, %s." % globalGame.at.name )
			TextDisplay( interface=screen, text="<N>".join(text), width=40, name="dead-title-screen", onDismiss=startGame)
		except IndexError:
			print "but seems to be invalid."
			print "You must move or remove this file before playing"
			print "a game with this character name."
			sys.stdout.flush()
			sys.exit(0)
	else:
		print "file does not exist, starting new game."
		sys.stdout.flush()
		globalGame = erlgame.Game( gameVersion, screen, name )
		screen.clearRepeats()
		text = []
		text.append( "After a days' journey by airship, you have reached your destination at last: a remote cave on an obscure island. Your mentor retreated to this island many years ago, and though it was isolated then, it was still a livelier place when you last saw it." )
		text.append( "It turns out that the rumours were true -- he really did go mad towards the end of his life. Now, he is no longer here, and he has left behind a cave filled with mechanical horrors of his own creation. Horrors that eventually began to think, began to build -- began preparing for something..." )
		text.append( "The last letter you received from him implored you to do only one thing: travel to this place, enter the cave, and destroy the <DARKBRASS>Emperor Engine</DARKBRASS> before it finishes preparing its mechanical army." )
		TextDisplay( interface=screen, text="<N>".join(text), width=60, name="dead-title-screen", onDismiss=startGame)

	screen.clearRepeats()

	
def startChooseName():
	okayNames = string.letters + string.digits + " " + "'_.-"
	nameQuery = StringQuery( allowed=okayNames, interface=screen, query="By what name shall I call you?", width=60, maximalLength = maxNameLength, inputBgColour=stdBackground, onAnswer = gotName, name = "initial-name-query" )

text = []
text.append( "<DARKBRASS>Emperor Engine</DARKBRASS>" )
text.append( "a roguelike by kaw" )
text.append( "" )
text.append( "<DARKBRASS>Version:</DARKBRASS> 1.1" )
text.append( "March 17, 2009" )
text.append( "" )
text.append( "[press space]" )
TextDisplay( interface=screen, text="<N>".join(text), width=60, name="initial-title-screen", onDismiss=startChooseName)

import string
while screen.elements.has_key( "initial-title-screen" ):
	screen.refresh()
	screen.waitForInput()
screen.sdl.clearscreen()
import rlinterface
def byeMessage():
	print "Thanks for playing!"
try:
	while screen.elements:
		screen.refresh()
		screen.waitForInput()
except (rlinterface.NoInputHandler, EndGameReally):
	byeMessage()
except PlayerDead:
	screen.messages.add( "<RED>You die...</RED> [press space to continue]" )
	ContinueOnSpace( screen, do = byeMessage )
	while screen.elements:
		screen.refresh()
		screen.waitForInput()
